package com.mh.service;

import com.mh.config.FireflyConfig;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
import org.springframework.core.ParameterizedTypeReference;

import java.util.HashMap;
import java.util.Map;

/**
 * Firefly III服务类：将AI解析后的记账数据同步到Firefly
 */
@Service
public class FireflyService {
    private final WebClient webClient;
    private final FireflyConfig fireflyConfig;

    // 构造函数注入配置和WebClient
    public FireflyService(FireflyConfig fireflyConfig) {
        this.fireflyConfig = fireflyConfig;
        this.webClient = WebClient.builder()
                .baseUrl(fireflyConfig.getApiUrl())
                .defaultHeader(HttpHeaders.AUTHORIZATION, "Bearer " + fireflyConfig.getApiToken())
                .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                .build();
    }

    /**
     * 同步记账交易到Firefly III
     * @param bookkeepingData AI解析后的记账数据（包含amount、category、date等）
     * @return Firefly III返回的交易ID
     */
    public Mono<Map<String, Object>> createTransaction(Map<String, Object> bookkeepingData) {
        // 1. 构造交易数据（原逻辑保留）
        Map<String, Object> transaction = new HashMap<>();
        transaction.put("type", "withdrawal"); // 交易类型（支出）
        transaction.put("amount", bookkeepingData.get("amount")); // 金额
        transaction.put("description", bookkeepingData.get("text")); // 描述
        transaction.put("date", bookkeepingData.get("date")); // 日期

        // 2. 调用Firefly III API并指定泛型返回类型
        // 注意：Authorization已在WebClient构建时通过defaultHeader设置，这里不需要重复设置
        return webClient
                .post()
                .uri("/api/v1/transactions") // Firefly III的标准交易API地址
                .bodyValue(transaction) // 发送交易数据
                .retrieve() // 发起请求并获取响应
                // 关键：用ParameterizedTypeReference明确返回类型是Map<String, Object>
                .bodyToMono(new ParameterizedTypeReference<Map<String, Object>>() {})
                // 添加错误处理
                .onErrorMap(e -> new RuntimeException("同步到Firefly III失败: " + e.getMessage(), e));
    }
}